package elements

import (
	"yizhuoyan/go-study/pdfgo/handyio"
)

var xrefKeywordBytes = []byte("xref")

type CrossReferenceSection struct {
	subsections []*CrossReferenceSubsection
}

func (this *CrossReferenceSection) GetObjIndexAndGn(objNum int) (int64, int) {
	for _, oneSub := range this.subsections {
		if rst := oneSub.GetEntry(objNum); rst != nil {
			return rst.GetIndexAt(), rst.objObjectVersionNumber
		}
	}
	return -1, 0
}
func (this *CrossReferenceSection) WriteSection(w handyio.PdfRawWriter) error {
	w.WriteBytes(xrefKeywordBytes)
	w.WriteEndOfLine()
	for _, one := range this.subsections {
		if err := one.WriteSubsection(w); err != nil {
			return err
		}
	}
	return nil
}

func (this *CrossReferenceSection) ReadSection(r handyio.PdfRawReader) error {
	if !r.NextBytesEquals(xrefKeywordBytes) {
		return r.NotSupport("无xref")
	}
	r.SkipNextWhiteSpaces()
	var rst = make([]*CrossReferenceSubsection, 0, 10)
	for true {
		var one = new(CrossReferenceSubsection)
		if err := one.ReadSubsection(r); err != nil {
			//说明已解析完毕
			if r.IsNotSupportError(err) {
				break
			}
			return err
		}
		rst = append(rst, one)
	}
	this.subsections = rst
	return nil
}
